<?php

namespace App\Console\Commands\CallingCards;

use App\Models\FeishuCallingCard\FeishuCallingCard;
use App\Service\CallingCards\CardService;
use App\Service\CallingCards\FeishuApiService;
use App\Service\OpenShop\Feishu\QualificationImageService;
use Illuminate\Console\Command;

class UpdateDepartment extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'feishuCallingCards:updateEmployeeDepartment';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新一级部门信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        FeishuCallingCard::query()
            ->orderBy('id', 'asc')
            ->chunk(100, function ($cards) {
                foreach ($cards as $card) {
                    $userInfo = FeishuApiService::getUserInfoByFeishuId($card->feishuId);
                    if (!isset($userInfo['code']) || $userInfo['code'] != 0) {
                        $this->warn("id:{$card->id} 跳过  " . json_encode($userInfo, JSON_UNESCAPED_UNICODE));
                        continue;
                    }
                    //获取一级部门
                    $departmentName = FeishuApiService::getDepartmentName($userInfo['data']['user']['department_ids'] ?? []);
                    if ($departmentName === '') {
                        $departmentInfo = FeishuApiService::getDepartment($userInfo['data']['user']['department_ids'][0] ?? '');
                        $departmentName = $departmentInfo['data']['department']['name'] ?? '';
                    }
                    // 真实姓名
                    $realname = $userInfo['data']['user']['name'] ?? '';
                    $nickname = $userInfo['data']['user']['nickname'] ?? '';
                    if (strlen($nickname)) {
                        $realname .= "($nickname)";
                    }
                    if (strlen($realname)) {
                        $card->realname = $realname;
                    }
                    if (strlen($departmentName)) {
                        $card->departmentName = $departmentName;
                    }
                    $jobTitle = $userInfo['data']['user']['job_title'] ?? '';
                    if (strlen($jobTitle)) {
                        $card->position = $jobTitle;
                    }
                    $card->save();

                    // 更新为空的微信分享图
                    if ($card->wxShareImg == '') {
                        $path = CardService::updateWxShareImg($card);
                        $this->info("path: {$path}");
                    }

                    $this->info("id:{$card->id} {$realname} OK");
                }
            });
    }
}
